import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Steps, 
  Select, 
  Form, 
  Radio, 
  Button, 
  Space, 
  Alert, 
  Table, 
  Tag,
  message,
  Spin
} from 'antd';
import { 
  DatabaseOutlined, 
  UserOutlined, 
  MailOutlined, 
  CheckCircleOutlined 
} from '@ant-design/icons';
import { request } from '@umijs/max';

const { Step } = Steps;

interface DataSource {
  id: number;
  name: string;
  type: string;
}

interface DataSourceTable {
  name: string;
  comment?: string;
  row_count?: number;
}

interface Variable {
  name: string;
  display_name: string;
  field_type: string;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
}

interface Recipient {
  email: string;
  name?: string;
  variables?: Record<string, any>;
}

interface IntegratedRecipientSelectorProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (recipients: Recipient[], variables: Variable[]) => void;
  dataSources: DataSource[];
}

const IntegratedRecipientSelector: React.FC<IntegratedRecipientSelectorProps> = ({
  visible,
  onCancel,
  onConfirm,
  dataSources,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  
  // 数据源相关状态
  const [selectedDataSource, setSelectedDataSource] = useState<DataSource | null>(null);
  const [tables, setTables] = useState<DataSourceTable[]>([]);
  const [selectedTable, setSelectedTable] = useState<string>('');
  const [tablesLoading, setTablesLoading] = useState(false);
  
  // 字段相关状态
  const [fields, setFields] = useState<Variable[]>([]);
  const [fieldsLoading, setFieldsLoading] = useState(false);
  const [emailField, setEmailField] = useState<string>('');
  const [nameField, setNameField] = useState<string>('');
  
  // 发送模式
  const [sendMode, setSendMode] = useState<'batch' | 'personalized'>('batch');
  
  // 收件人预览
  const [recipients, setRecipients] = useState<Recipient[]>([]);
  const [recipientsLoading, setRecipientsLoading] = useState(false);

  // 重置状态
  const resetState = () => {
    setCurrentStep(0);
    setSelectedDataSource(null);
    setTables([]);
    setSelectedTable('');
    setFields([]);
    setEmailField('');
    setNameField('');
    setSendMode('batch');
    setRecipients([]);
    form.resetFields();
  };

  // 获取表列表
  const fetchTables = async (dataSourceId: number) => {
    setTablesLoading(true);
    try {
      const response = await request(`/api/data-sources/${dataSourceId}/tables`, {
        method: 'GET',
      });
      setTables(response.tables || []);
      if (response.tables && response.tables.length > 0) {
        setSelectedTable(response.tables[0].name);
      }
    } catch (error: any) {
      message.error(error.message || '获取表列表失败');
    } finally {
      setTablesLoading(false);
    }
  };

  // 获取字段列表
  const fetchFields = async (dataSourceId: number, tableName: string) => {
    setFieldsLoading(true);
    try {
      const response = await request(
        `/api/data-sources/${dataSourceId}/tables/${tableName}/fields`,
        {
          method: 'GET',
          params: { identify_types: true },
        }
      );
      setFields(response || []);
      
      // 自动选择邮箱和姓名字段
      const emailFields = response.filter((f: Variable) => f.is_email);
      const nameFields = response.filter((f: Variable) => f.is_name);
      
      if (emailFields.length > 0) {
        setEmailField(emailFields[0].name);
      }
      if (nameFields.length > 0) {
        setNameField(nameFields[0].name);
      }
    } catch (error: any) {
      message.error(error.message || '获取字段列表失败');
    } finally {
      setFieldsLoading(false);
    }
  };

  // 预览收件人
  const previewRecipients = async () => {
    if (!selectedDataSource || !selectedTable || !emailField) return;

    setRecipientsLoading(true);
    try {
      const response = await request(
        `/api/data-sources/${selectedDataSource.id}/preview`,
        {
          method: 'GET',
          params: {
            table_name: selectedTable,
            limit: 100,
          },
        }
      );

      const emailIndex = response.columns.indexOf(emailField);
      const nameIndex = nameField ? response.columns.indexOf(nameField) : -1;

      const recipientList = response.data.map((row: any[], index: number) => {
        const recipient: Recipient = {
          email: row[emailIndex] || '',
        };

        if (nameIndex >= 0 && row[nameIndex]) {
          recipient.name = row[nameIndex];
        }

        // 添加所有字段作为变量
        const variables: Record<string, any> = {};
        response.columns.forEach((col: string, colIndex: number) => {
          variables[col] = row[colIndex];
        });
        recipient.variables = variables;

        return recipient;
      }).filter((r: Recipient) => r.email); // 过滤掉没有邮箱的记录

      setRecipients(recipientList);
    } catch (error: any) {
      message.error(error.message || '预览收件人失败');
    } finally {
      setRecipientsLoading(false);
    }
  };

  // 处理数据源选择
  const handleDataSourceChange = (dataSourceId: number) => {
    const dataSource = dataSources.find(ds => ds.id === dataSourceId);
    if (dataSource) {
      setSelectedDataSource(dataSource);
      fetchTables(dataSourceId);
    }
  };

  // 处理表选择
  const handleTableChange = (tableName: string) => {
    setSelectedTable(tableName);
    if (selectedDataSource) {
      fetchFields(selectedDataSource.id, tableName);
    }
  };

  // 下一步
  const handleNext = async () => {
    if (currentStep === 0) {
      // 验证第一步
      if (!selectedDataSource || !selectedTable || !emailField) {
        message.warning('请完成数据源和字段配置');
        return;
      }
      setCurrentStep(1);
    } else if (currentStep === 1) {
      // 预览收件人
      await previewRecipients();
      setCurrentStep(2);
    }
  };

  // 上一步
  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  // 确认选择
  const handleConfirm = () => {
    onConfirm(recipients, fields);
    resetState();
  };

  // 取消
  const handleCancel = () => {
    onCancel();
    resetState();
  };

  useEffect(() => {
    if (!visible) {
      resetState();
    }
  }, [visible]);

  const recipientColumns = [
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      render: (email: string) => (
        <Space>
          <MailOutlined style={{ color: '#1890ff' }} />
          {email}
        </Space>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => name || '-',
    },
    {
      title: '变量数量',
      key: 'variables',
      render: (_, record: Recipient) => (
        <Tag>{Object.keys(record.variables || {}).length} 个变量</Tag>
      ),
    },
  ];

  return (
    <Modal
      title="选择收件人"
      open={visible}
      onCancel={handleCancel}
      width={800}
      footer={null}
    >
      <Steps current={currentStep} style={{ marginBottom: 24 }}>
        <Step title="选择数据源" icon={<DatabaseOutlined />} />
        <Step title="设置过滤条件" icon={<UserOutlined />} />
        <Step title="预览收件人" icon={<CheckCircleOutlined />} />
      </Steps>

      {currentStep === 0 && (
        <Form form={form} layout="vertical">
          <Form.Item label="数据源" required>
            <Select
              placeholder="请选择数据源"
              value={selectedDataSource?.id}
              onChange={handleDataSourceChange}
              options={dataSources.map(ds => ({
                label: (
                  <Space>
                    <DatabaseOutlined />
                    {ds.name} ({ds.type})
                  </Space>
                ),
                value: ds.id,
              }))}
            />
          </Form.Item>

          {selectedDataSource && (
            <Form.Item label="数据表" required>
              <Select
                placeholder="请选择数据表"
                value={selectedTable}
                onChange={handleTableChange}
                loading={tablesLoading}
                options={tables.map(table => ({
                  label: (
                    <div>
                      <div>{table.name}</div>
                      {table.comment && (
                        <div style={{ fontSize: '12px', color: '#666' }}>
                          {table.comment}
                        </div>
                      )}
                      {table.row_count !== null && (
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          约 {table.row_count} 行
                        </div>
                      )}
                    </div>
                  ),
                  value: table.name,
                }))}
              />
            </Form.Item>
          )}

          {selectedTable && (
            <Spin spinning={fieldsLoading}>
              <Form.Item label="邮箱字段" required>
                <Select
                  placeholder="请选择邮箱字段"
                  value={emailField}
                  onChange={setEmailField}
                  options={fields.map(field => ({
                    label: (
                      <Space>
                        {field.is_email && <MailOutlined style={{ color: '#1890ff' }} />}
                        {field.display_name || field.name}
                        <Tag size="small">{field.field_type}</Tag>
                      </Space>
                    ),
                    value: field.name,
                  }))}
                />
              </Form.Item>

              <Form.Item label="姓名字段（可选）">
                <Select
                  placeholder="请选择姓名字段"
                  value={nameField}
                  onChange={setNameField}
                  allowClear
                  options={fields.map(field => ({
                    label: (
                      <Space>
                        {field.is_name && <UserOutlined style={{ color: '#52c41a' }} />}
                        {field.display_name || field.name}
                        <Tag size="small">{field.field_type}</Tag>
                      </Space>
                    ),
                    value: field.name,
                  }))}
                />
              </Form.Item>
            </Spin>
          )}

          <Form.Item label="发送模式">
            <Radio.Group value={sendMode} onChange={(e) => setSendMode(e.target.value)}>
              <Radio value="batch">批量发送 - 所有人收到相同内容</Radio>
              <Radio value="personalized">个性化发送 - 每人收到不同内容</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      )}

      {currentStep === 1 && (
        <div>
          <Alert
            message="过滤条件设置"
            description="您可以在这里设置收件人过滤条件，暂时跳过此步骤。"
            type="info"
            style={{ marginBottom: 16 }}
          />
        </div>
      )}

      {currentStep === 2 && (
        <div>
          <Alert
            message={`找到 ${recipients.length} 个收件人`}
            description={`邮箱字段: ${emailField}${nameField ? `, 姓名字段: ${nameField}` : ''}`}
            type="success"
            style={{ marginBottom: 16 }}
          />
          
          <Table
            columns={recipientColumns}
            dataSource={recipients}
            rowKey="email"
            loading={recipientsLoading}
            pagination={{ pageSize: 10 }}
            size="small"
          />
        </div>
      )}

      <div style={{ marginTop: 24, textAlign: 'right' }}>
        <Space>
          <Button onClick={handleCancel}>取消</Button>
          {currentStep > 0 && (
            <Button onClick={handlePrev}>上一步</Button>
          )}
          {currentStep < 2 && (
            <Button 
              type="primary" 
              onClick={handleNext}
              disabled={currentStep === 0 && (!selectedDataSource || !selectedTable || !emailField)}
            >
              下一步
            </Button>
          )}
          {currentStep === 2 && (
            <Button type="primary" onClick={handleConfirm}>
              确认选择 ({recipients.length} 人)
            </Button>
          )}
        </Space>
      </div>
    </Modal>
  );
};

export default IntegratedRecipientSelector;
